package cn.xsw.common;

import cn.hutool.json.JSONUtil;
import cn.xsw.utils.IResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class ResultBody {
    private  Boolean success;
    /**
     * 响应代码
     */
    private Integer code;

    /**
     * 响应消息
     */
    private String message;

    /**
     * 响应结果
     */
    private Object result;

    private ResultBody(BaseErrorInfoInterface errorInfo) {
        this.success=errorInfo.getResultCode()==CommonEnum.SUCCESS.getResultCode();
        this.code = errorInfo.getResultCode();
        this.message = errorInfo.getResultMsg();
    }

    private ResultBody(Integer code, String message, Object result) {
        this.success = code==CommonEnum.SUCCESS.getResultCode();
        this.code = code;
        this.message = message;
        this.result = result;
    }

    /**
     * 成功
     *
     * @return
     */
    public static ResultBody success() {
        return success(null);
    }
    /**
     * 成功
     * @param data
     * @return
     */
    public static ResultBody success(Object data) {
        return new ResultBody(CommonEnum.SUCCESS).setResult(data);
    }
    /**
     * 失败
     */
    public static ResultBody error(BaseErrorInfoInterface errorInfo) {
        return new ResultBody(errorInfo);
    }
    /**
     * 失败
     */
    public static ResultBody error(Integer code, String message) {
        return new ResultBody(code,message,null);
    }

    /**
     * 失败
     */
    public static ResultBody error( String message) {
        return new ResultBody(-1,message,null);
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }

    public ResultBody page(IPage ipage) {
            return this.setResult(new IPageBody().setResult(ipage.getRecords()).setTotal(ipage.getTotal()).setPageNo((ipage.getCurrent() / ipage.getSize()) + 1).setPageSize(ipage.getSize()));
    }
}
@Data
@Accessors(chain = true)
class IPageBody {
    private Long pageNo;

    private Long pageSize;

    private Long total;

    private Object result;
}

